# -*- coding: utf8 -*-
import json
import time
import os
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException

class ASR:
    # 阿里云配置
    REGION_ID = "cn-shanghai"
    DOMAIN = "filetrans.cn-shanghai.aliyuncs.com"
    PRODUCT = "nls-filetrans"
    API_VERSION = "2018-08-17"
    APP_KEY = os.getenv('ALI_VOICE_APPKEY')

    @staticmethod
    def transcribe(file_url):
        """
        音频文件转写静态方法
        :param audio_file_path: 音频文件路径
        :return: 成功返回识别文本，失败返回None
        """
        try:
            client = AcsClient(
                os.getenv('ALIYUN_AK_ID'),
                os.getenv('ALIYUN_AK_SECRET'),
                ASR.REGION_ID
            )
            # 提交录音文件识别请求
            task_id = ASR._submit_task(client, file_url)
            if not task_id:
                return None
            print(f'task_id: {task_id}')
            # 轮询获取结果
            result = ASR._get_task_result(client, task_id)
            print(f'result: {result}')
            return result
        except Exception as e:
            print(f"转写过程出错: {str(e)}")
            return None

    @staticmethod
    def _submit_task(client, file_path):
        """提交转写任务"""
        request = CommonRequest()
        request.set_domain(ASR.DOMAIN)
        request.set_version(ASR.API_VERSION)
        request.set_product(ASR.PRODUCT)
        request.set_action_name("SubmitTask")
        request.set_method('POST')

        task = {
            "appkey": ASR.APP_KEY,
            "file_link": file_path,
            "version": "4.0",
            "enable_words": False,
            "enable_sample_rate_adaptive": True
        }
        
        request.add_body_params("Task", json.dumps(task))

        try:
            response = client.do_action_with_exception(request)
            response = json.loads(response)
            if response["StatusText"] == "SUCCESS":
                return response["TaskId"]
            print(f"提交任务失败: {response['StatusText']}")
            return None
        except Exception as e:
            print(f"提交任务异常: {str(e)}")
            return None

    @staticmethod
    def _get_task_result(client, task_id):
        """获取转写结果"""
        request = CommonRequest()
        request.set_domain(ASR.DOMAIN)
        request.set_version(ASR.API_VERSION)
        request.set_product(ASR.PRODUCT)
        request.set_action_name("GetTaskResult")
        request.set_method('GET')
        request.add_query_param("TaskId", task_id)

        while True:
            try:
                # print('loop')
                response = client.do_action_with_exception(request)
                response = json.loads(response)
                # print(f'response: {response}')
                status = response["StatusText"]
                
                if status == "RUNNING" or status == "QUEUEING":
                    time.sleep(2)
                    continue
                    
                if status == "SUCCESS":
                    return response["Result"]
                    
                print(f"转写失败: {status}")
                return None
                
            except Exception as e:
                print(f"获取结果异常: {str(e)}")
                return None


if __name__ == '__main__':
    pass